package com.wollo.config;

import com.wollo.handle.MyLoginSuccessHandle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //配置公告的拦截信息
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //1. 配置session管理
        //2. 配置表单提交
        http.formLogin().loginPage("/login")
                .loginProcessingUrl("/userLogin")
                .successHandler(new MyLoginSuccessHandle())
                .passwordParameter("pwd")
                .usernameParameter("username");
        //3. 配置RememberMe
        //4. 配置退出
        //5. 配置拦截
        http.authorizeRequests()
//                .antMatchers("/login").permitAll()
//                .antMatchers("/layui/**").permitAll()
//                .antMatchers("/images/**").permitAll()
//                .antMatchers("/js/**").permitAll()
//                .antMatchers("/css/**").permitAll()
//                .antMatchers("/plugins/**").permitAll()
                .antMatchers("/**").permitAll()
            .anyRequest().authenticated();
        //6. 配置权限校验失败跳转
        //7. 关闭csrf防护
        http.csrf().disable();
    }
    //配置密码解析器的bean
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    //配置RememberMe的bean
    @Bean
    public JdbcTokenRepositoryImpl jdbcTokenRepository(DataSource dataSource) {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        // jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    //配置SessionRegistry的bean
    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }
}
